package com.ysfxt.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.ysfxt.mapper.SysTeacherMapper;
import com.ysfxt.model.SysTeacher;
import com.ysfxt.utils.MD5;

import java.util.List;

/**
 * @author 盐酸氟西汀
 * @create 2024/3/30 15:39
 * @email 480738950@qq.com
 */
public class ExcelListener <SysTeacher> extends AnalysisEventListener<com.ysfxt.model.SysTeacher> {
    
    /**
     每隔100条存储数据库，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<com.ysfxt.model.SysTeacher> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    
    //获取mapper对象
    private SysTeacherMapper sysTeacherMapper;
    
    public ExcelListener(SysTeacherMapper sysTeacherMapper) {
        this.sysTeacherMapper = sysTeacherMapper;
    }
    
    @Override
    public void invoke(com.ysfxt.model.SysTeacher t, AnalysisContext analysisContext) {
        //加密一下
        t.setPassword(MD5.encrypt(t.getPassword()));
        //把每行对象数据放到cachedDataList中
        cachedDataList.add(t);
        //达到最大值了，存储一次数据库
        if(cachedDataList.size()>=BATCH_COUNT){
            //调用方法批量添加到数据库
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }
    
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }
    
    //批量插入
    private void saveData() {
        sysTeacherMapper.batchInsert(cachedDataList);
    }
}